#include "settingsmenu.h"
#include "ui_settingsmenu.h"
#include "../pluginSDK/UploaderInterface.h"
#include <QKeyEvent>
#include "settings.h"
#include <QDir>
#include <QPluginLoader>
#include <QDialog>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QWidget>

SettingsMenu::SettingsMenu(QWidget *parent) :
    QTabWidget(parent),
    ui(new Ui::SettingsMenu)
{
    ui->setupUi(this);
    this->setFixedSize(this->size());
    ui->hotkeyLineEdit->installEventFilter(this);
    LoadConfig();
    ui->hotkeyLineEdit->setText(Settings::instance().getKey());
    setConnections();
}

void SettingsMenu::setConnections() {
    connect(ui->reloadButton, SIGNAL(clicked()), SLOT(reloadPlugins()));
    connect(ui->okButton, SIGNAL(clicked()), SLOT(onOkButtonClicked()));
    connect(ui->optionsButton, SIGNAL(clicked()), SLOT(onOptionsButtonClicked()));
    connect(ui->aboutButton, SIGNAL(clicked()), SLOT(onAboutButtonClicked()));
}

SettingsMenu::~SettingsMenu()
{
    delete ui;
}

bool SettingsMenu::eventFilter(QObject *obj, QEvent *event) {
    Q_UNUSED(obj);

    if (event->type() == QEvent::KeyPress) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

        QKeySequence key = keyEvent->modifiers() + keyEvent->key();

        setKey(key);
        emit hotkeyLineEditHasBeenChanged(key);

        return true;
    }
    else {
        return false;
    }
}

void SettingsMenu::setKey(const QKeySequence &key) {
    ui->hotkeyLineEdit->setText(key.toString());
}

QKeySequence SettingsMenu::getKey() {
    return QKeySequence(ui->hotkeyLineEdit->text());
}

void SettingsMenu::LoadConfig()
{
    QString path;
    QString plugin_name;
    QString defaultPluginName;
    path=path.append(QApplication::applicationDirPath());

    path=path.append("/Plugins");

    QDir dir(path);

    QStringList::Iterator it;

    QStringList files = dir.entryList(QDir::NoDotAndDotDot | QDir::NoSymLinks | QDir::Files);
    defaultPluginName = Settings::instance().getPluginName();

    it=files.begin();
    ui->comboBox->clear();
    int index=0;
    int i=0;
    while(it!=files.end())
    {
        QString pluginFileName = QFileInfo(*it).fileName();

        if(pluginFileName.length() > 2)
        {
            // loading plugin
            QPluginLoader pl;
            QString str;

            str.append(QApplication::applicationDirPath() + "/Plugins/" + pluginFileName);
            pl.setFileName(str);
            QObject *tmp=pl.instance();
            UploaderInterface *upl=qobject_cast<UploaderInterface*>(tmp);
            upl->GetPluginName(plugin_name);
            pluginsList.append(qMakePair(pluginFileName, plugin_name));
            //end loading file

            if(!QString::compare(defaultPluginName, plugin_name))
            {
                index=i;
            }
            else
            {
                i++;
            }
            ui->comboBox->addItem(plugin_name);
            delete tmp;
            delete upl; // don't forget to clean up :)
        }
        it++;
    }

    ui->comboBox->setCurrentIndex(index);
}

void SettingsMenu::reloadPlugins()
{
    LoadConfig();
}

void SettingsMenu::onOkButtonClicked()
{
    Settings::instance().setPluginName(ui->comboBox->currentText());
//    Settings::instance().setPluginFileName(selectedPluginFileName());
    Settings::instance().setUploader(selectedPluginFileName());
    this->close();
}

QString SettingsMenu::selectedPluginFileName()
{
    QList<QPair<QString, QString> >::Iterator it;
    it = pluginsList.begin();

    while(it != pluginsList.end())
    {
        QPair<QString, QString> pair = QPair<QString, QString>(*it);
        if(ui->comboBox->currentText() == pair.second)
        {
            return pair.first;
        }
        else
        {
            it++;
        }

    }

    return QString::fromAscii("");
}

void SettingsMenu::onOptionsButtonClicked() {

    QPluginLoader pl;
    QString str;
    QString plugName = selectedPluginFileName();
    //str.append(QApplication::applicationDirPath() + "/Plugins/" + ui->comboBox->itemText(ui->comboBox->currentIndex()));
    str.append(QApplication::applicationDirPath() + "/Plugins/" + plugName);


    pl.setFileName(str);
    QObject *tmp=pl.instance();
    UploaderInterface *upl=qobject_cast<UploaderInterface*>(tmp);
    constructSettingsWindowDraft();
    upl->ShowOptions(settingsWindowDraft);    
}

void SettingsMenu::onAboutButtonClicked()
{
//    QPluginLoader pl;
//    QString str;
//    str=str.append(QApplication::applicationDirPath() +"/Plugins/" + ui->comboBox->itemText(ui->comboBox->currentIndex()));

//    pl.setFileName(str);

//    QObject *tmp = pl.instance();

//    UploaderInterface * upl = qobject_cast<UploaderInterface *>(tmp);
}

void SettingsMenu::constructSettingsWindowDraft() {
    /* In my opinion we'd better to use QDialog instead of QWidget.
     * The reason is possibility of using QDialogButtonBox, that
     * makes button looks as they ought to in any platform.
     * Also maybe there is a possibility to use QDialogButtonBox
     * with QWidget, but I'm not sure...
     */
    settingsWindowDraft = new QDialog();
    settingsWindowDraft->setAttribute(Qt::WA_DeleteOnClose);
    connect(qApp, SIGNAL(aboutToQuit()), settingsWindowDraft, SLOT(close()));
}
